package com.emm.yixun.system.service.impl.manage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.MsgSettingService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.MsgSetting;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.MsgSettingDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.TempTypeEnum;
import com.emm.yixun.common.utils.MsgUtil;

@Service("customerCareNoticeManage")
public class CustomerCareNoticeManage {

	@Autowired
	private MsgSettingService msgSettingService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private UserService userService;
	@Autowired
	private SysNoticeManage sysNoticeManage;
	
	/**
	 * 插入消息
	 * @param reqDto
	 * @return
	 */
	public CommonResDTO createNotice() {
		CommonResDTO resDto = new CommonResDTO();
		resDto.setResult("0");
		try{
			//1、根据sys_tm_msg_setting设置,获取客户关怀提醒时间
			MsgSettingDto settingDto = new MsgSettingDto();
			settingDto.setTempType(TempTypeEnum.RE07.getNo());
			//不同的商户有不同的时间设置
			List<MsgSetting> settingList = msgSettingService.selectListByDto(settingDto);
			if(settingList != null){
				//1、生日提前提醒模板 NT38
				String birthBeforeTemp = "客户${customer}${beforeDay}天后生日,快快慰问一下吧！";
				//2、生日当天提醒模板 NT39
				String birthCurrTemp = "客户${customer}今天生日,快去送上你的祝福吧！";
				//3、纪念日提前提醒模板 NT40
				String weddingBeforeTemp = "你的客户${customer}将在${beforeDay}天后结婚纪念日,快去送上你的祝福吧！";
				//4、纪念日当天提醒模板 NT41
				String weddingCurrTemp = "你的客户${customer}今天结婚纪念日,快去送上你的祝福吧！";
				
				//消息内容模板
				DictionaryDto dicDto = new DictionaryDto();
 				dicDto.setDictionaryType("NT");
 				List<Dictionary> dicList = dictionaryService.selectListByDto(dicDto);
 				if(dicList != null){
 					for(Dictionary dic: dicList){
 	 					if("NT38".equals(dic.getDictionaryValue())){
 	 						birthBeforeTemp = dic.getDictionaryName();
 	 					}else if("NT39".equals(dic.getDictionaryValue())){
 	 						birthCurrTemp = dic.getDictionaryName();
 	 					}else if("NT40".equals(dic.getDictionaryValue())){
 	 						weddingBeforeTemp = dic.getDictionaryName();
 	 					}else if("NT41".equals(dic.getDictionaryValue())){
 	 						weddingCurrTemp = dic.getDictionaryName();
 	 					}
 	 				}
 				}
 				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
 				//遍历客户关怀消息设置,查询不同商户的相关客户
 				for(MsgSetting setting: settingList){
 					//提前提醒触发天数
 					int attackTime = setting.getAttackTime() == null?7:setting.getAttackTime(); //默认提前7天
 					//当天提醒小时
 					int currHour = setting.getCurrHour() == null?8:setting.getCurrHour(); //默认时间为8点整
 					//当天提醒分钟
 					int currMinute = setting.getCurrMinute() == null?0:setting.getCurrMinute();
 					
 					//2、获取客户中生日在此范围的相关人员
 					Map<Long, Customer> birthCusMap = new HashMap<Long, Customer>();
 					CustomerDto cusDto = new CustomerDto();
 					cusDto.setMerchantId(setting.getMerchantId());
 					cusDto.setBirth(attackTime+"");
 					List<CustomerDto> cusList = customerService.setBirthByDto(cusDto);
 					//遍历生日相关客户
 					for(int i = 0; i < cusList.size(); i++){
 						CustomerDto customer = (CustomerDto)cusList.get(i);
 						if(null==customer)continue;
 						
 						//查询客户归属人
						List<User> userList = new ArrayList<User>();
						UserDto entity = new UserDto();
						entity.setUserCode(customer.getUserCode());
						User user = userService.selectByDto(entity);
						
						Map<String,String> replaceValuesMap=new HashMap<String,String>();
 						String sendMsg = "";
 						Map<String, String> noticeParamMap = new HashMap<String, String>();
 						String diffDay = customer.getDiffDay();
 						if(!"0".equals(diffDay)){
	 						//生日提前通知
 							//当相隔天数为0时表示当天生日，不走提前推送方法
	 						sendMsg = birthBeforeTemp.replace("${customer}", customer.getCustomerName())
	 								.replace("${beforeDay}", diffDay);
							noticeParamMap.put("noticeDicId", "197");
							noticeParamMap.put("noticeTempType", "NT38");
							noticeParamMap.put("sendMsg", sendMsg);
							noticeParamMap.put("title", "客户关怀,生日提前提醒");
							noticeParamMap.put("merchantId", String.valueOf(customer.getMerchantId()));
							noticeParamMap.put("projectCode", customer.getProjectCode());
							noticeParamMap.put("userCode", customer.getUserCode());
							noticeParamMap.put("accessCode", customer.getAccessCode());
							noticeParamMap.put("createUserId", String.valueOf(setting.getCreateUserId()));
							
							/*
							 * (ym) 提醒内容增加超链接 start
							 * */
							replaceValuesMap.put(MsgUtil.ROOM_ID, "");
							replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
							replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
							replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customer.getCustomerName());
							replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
							replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
					    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
					    	/*
							 * (ym) 提醒内容增加超链接 end
							 * */
							
					    	//判断是否已有消息
					    	CommonResDTO common1 = sysNoticeManage.isRepeated(noticeParamMap);
					    	if("1".equals(common1.getResult())){
					    		continue;
					    	}
					    	
							if(user != null){
								userList.add(user);
								sysNoticeManage.createNotice(noticeParamMap, userList);
							}
 						}
		 				
						//当前日期+触发天数 = 即将过生日的日期
	 					Calendar calendar = Calendar.getInstance();
	 					if(StringUtils.isNotBlank(customer.getDiffDay())){
	 						calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt(diffDay));
	 					}
	 					int year = calendar.get(Calendar.YEAR);
	 					int month = calendar.get(Calendar.MONTH) + 1;
	 					int day = calendar.get(Calendar.DAY_OF_MONTH);
		 				//生日当天通知
 						sendMsg = birthCurrTemp.replace("${customer}", customer.getCustomerName());
 						noticeParamMap = new HashMap<String, String>();
						noticeParamMap.put("noticeDicId", "198");
						noticeParamMap.put("noticeTempType", "NT39");
						noticeParamMap.put("sendMsg", sendMsg);
						noticeParamMap.put("timerNotice", year+"-"+month+"-"+day+" "+currHour+":"+currMinute+":10");
						noticeParamMap.put("title", "客户关怀,生日当天提醒");
						noticeParamMap.put("merchantId", String.valueOf(customer.getMerchantId()));
						noticeParamMap.put("projectCode", customer.getProjectCode());
						noticeParamMap.put("userCode", customer.getUserCode());
						noticeParamMap.put("accessCode", customer.getAccessCode());
						noticeParamMap.put("createUserId", String.valueOf(setting.getCreateUserId()));
						/*
						 * (ym) 提醒内容增加超链接 start
						 * */
						/*
						 * (ym) 提醒内容增加超链接 start
						 * */
						replaceValuesMap.put(MsgUtil.ROOM_ID, "");
						replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
						replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
						replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customer.getCustomerName());
						replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
						replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
				    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
				    	/*
						 * (ym) 提醒内容增加超链接 end
						 * */
				    	//判断是否已有消息
				    	CommonResDTO common2 = sysNoticeManage.isRepeated(noticeParamMap);
				    	if("1".equals(common2.getResult())){
				    		continue;
				    	}
				    	
						if(user != null){
							userList.add(user);
							sysNoticeManage.createNotice(noticeParamMap, userList);
						}
 					}
 					
 					//3、获取客户中纪念日在此范围的相关人员
 					Map<Long, Customer> weddingCusMap = new HashMap<Long, Customer>();
 					CustomerDto weddingCusDto = new CustomerDto();
 					weddingCusDto.setMerchantId(setting.getMerchantId());
 					weddingCusDto.setWeddingDate(attackTime+"");
 					List<CustomerDto> weddingCusList = customerService.setBirthByDto(weddingCusDto);
 					//遍历纪念日相关客户
 					for(int i = 0; i < weddingCusList.size(); i++){
 						CustomerDto customer = (CustomerDto)weddingCusList.get(i);
 						
 						//查询客户归属人
						List<User> userList = new ArrayList<User>();
						UserDto entity = new UserDto();
						entity.setUserCode(customer.getUserCode());
						User user = userService.selectByDto(entity);
 						
 						Map<String,String> replaceValuesMap=new HashMap<String,String>();
 						String sendMsg = "";
 						Map<String, String> noticeParamMap = new HashMap<String, String>();
 						String diffWeddingDay = customer.getDiffWeddingDay();
 						if(!"0".equals(diffWeddingDay)){
	 						//纪念日提前通知
	 						sendMsg = weddingBeforeTemp.replace("${customer}", customer.getCustomerName())
	 								.replace("${beforeDay}", diffWeddingDay);
							noticeParamMap.put("noticeDicId", "199");
							noticeParamMap.put("noticeTempType", "NT40");
							noticeParamMap.put("sendMsg", sendMsg);
							noticeParamMap.put("title", "客户关怀,纪念日提前提醒");
							noticeParamMap.put("merchantId", String.valueOf(customer.getMerchantId()));
							noticeParamMap.put("projectCode", customer.getProjectCode());
							noticeParamMap.put("userCode", customer.getUserCode());
							noticeParamMap.put("accessCode", customer.getAccessCode());
							noticeParamMap.put("createUserId", String.valueOf(setting.getCreateUserId()));
							
							/*
							 * (ym) 提醒内容增加超链接 start
							 * */
							replaceValuesMap.put(MsgUtil.ROOM_ID, "");
							replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
							replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
							replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customer.getCustomerName());
							replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
							replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
					    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
					    	/*
							 * (ym) 提醒内容增加超链接 end
							 * */
							
							//判断是否已有消息
					    	CommonResDTO common1 = sysNoticeManage.isRepeated(noticeParamMap);
					    	if("1".equals(common1.getResult())){
					    		continue;
					    	}
							
							if(user != null){
								userList.add(user);
								sysNoticeManage.createNotice(noticeParamMap, userList);
							}
 						}
		 				
						//当前日期+触发天数 = 即将过生日的日期
	 					Calendar calendar = Calendar.getInstance();
	 					if(StringUtils.isNotBlank(customer.getDiffDay())){
	 						calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt(diffWeddingDay));
	 					}
	 					int year = calendar.get(Calendar.YEAR);
	 					int month = calendar.get(Calendar.MONTH) + 1;
	 					int day = calendar.get(Calendar.DAY_OF_MONTH);
		 				//纪念日当天通知
 						sendMsg = weddingCurrTemp.replace("${customer}", customer.getCustomerName());
 						noticeParamMap = new HashMap<String, String>();
						noticeParamMap.put("noticeDicId", "200");
						noticeParamMap.put("noticeTempType", "NT41");
						noticeParamMap.put("sendMsg", sendMsg);
						noticeParamMap.put("timerNotice", year+"-"+month+"-"+day+" "+currHour+":"+currMinute+":10");
						noticeParamMap.put("title", "客户关怀,纪念日当天提醒");
						noticeParamMap.put("merchantId", String.valueOf(customer.getMerchantId()));
						noticeParamMap.put("projectCode", customer.getProjectCode());
						noticeParamMap.put("userCode", customer.getUserCode());
						noticeParamMap.put("accessCode", customer.getAccessCode());
						noticeParamMap.put("createUserId", String.valueOf(setting.getCreateUserId()));
						/*
						 * (ym) 提醒内容增加超链接 start
						 * */
						replaceValuesMap.put(MsgUtil.ROOM_ID, "");
						replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
						replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
						replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customer.getCustomerName());
						replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
						replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
				    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
				    	/*
						 * (ym) 提醒内容增加超链接 end
						 * */
				    	
						//判断是否已有消息
				    	CommonResDTO common2 = sysNoticeManage.isRepeated(noticeParamMap);
				    	if("1".equals(common2.getResult())){
				    		continue;
				    	}
						
						if(user != null){
							userList.add(user);
							sysNoticeManage.createNotice(noticeParamMap, userList);
						}
 					}
 				}
			}
			resDto.setResult("1");
		}catch(Exception e){
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("添加提醒消息失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
}
